const express = require('express');
const fs = require('fs');
const time = require('time-stamp');
const app = express();
const path = require('path');
const svg = require('svg-captcha');
const session = require('cookie-session')
app.listen(3000);
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use((req, res, next) => {
    req.time = time('YYYY年MM月DD日  HH:mm:ss');
    next();
});
app.use(session({
    keys: ['llll', 'iiii'],
}))
app.get('/code', (req, res) => {
    let captcha = svg.create({
        size: 4,
        ignoreChars: 'oOiI1lL',
        color: true,
        noise: 3,
        background: '#ccc'
    })
    req.session.yzm = captcha.text;
    console.log(captcha.text);
    res.type('svg');
    res.send(captcha.data);

})
// 获取persons.json数据
let dir = path.join(__dirname, '/persons.json');
let data = fs.readFileSync(dir, 'utf-8');
data = JSON.parse(data);
// 渲染页面
app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, 'register.html'))
})


// 注册逻辑
app.post('/register', (req, res, next) => {

    let { tel, pass, pass2, yzm } = req.body;
    console.log(tel, pass, pass2, yzm);

    // 传参不能为空
    if (!tel || !pass || !pass2) {
        next('请输入有效内容');
        return;
    }
    // 判断两次密码是否一致
    if (pass != pass2) {
        next('两次密码输入不一致');
        return;
    }
    // 判断是否存在
    let s = data.find(item => item.username == tel);
    if (s) {
        next('用户名已存在');
        return;
    }
    // 验证码
    console.log(req.session.yzm);
    if(!yzm){
        next('验证码为空');
        return;
    }
    if (req.session.yzm != yzm) {
        next('验证码输入有误');
        return;
    }
    // 用户名不存在可注册
    data.push({ username: tel, password: pass, time: req.time });
    fs.writeFileSync(dir, JSON.stringify(data));
    res.send({ code: 200, msg: '注册成功' })

})
app.use((err, req, res, next) => {
    res.send({ code: 400, msg: err })
})
